package com.zzty.zzlp.serviceimpl;

import com.zzty.zzlp.commom.PropertyUtil;
import com.zzty.zzlp.dao.ChatMapper;
import com.zzty.zzlp.entity.Chat;
import com.zzty.zzlp.entity.ChatBuffer;
import com.zzty.zzlp.entity.ChatUser;
import com.zzty.zzlp.entity.User;
import com.zzty.zzlp.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

@Service
public class ChatServiceImpl implements ChatService {

    /**
     *
     */
    @Autowired
    ChatMapper chatMapper;

    @Override
    public List<User> searchUsers() {

        return chatMapper.searchUsers();
    }

    @Override
    public void createChat(Chat chat) {
        chatMapper.createChat(chat);
    }

    @Override
    public List<ChatUser> searchUsersAndLastMessage(Integer userId) {

        List<ChatUser> chatUsers = new ArrayList<ChatUser>();
        List<User> userList = chatMapper.searchUsers();
        for (int i = 0; i < userList.size(); i++) {
            if (userId.equals(userList.get(i).getId())) {
//               System.out.println(user.getId());
//               System.out.println(userList.get(i).getId());
                userList.remove(i);

            }

        }
        for (int i = 0; i < userList.size(); i++) {
            ChatUser chatUser = new ChatUser();
            chatUser.setName(userList.get(i).getName());
            chatUser.setUserId(userList.get(i).getId());

            List<Chat> chatList = chatMapper.searchFromMessage(userId, userList.get(i).getId());
            for (Chat chat : chatList) {
                if (chat == null) {
                    chatUser.setLastMessage("");
                    chatUser.setLastMessageType("");
                } else {
                    chatUser.setLastMessage(chat.getMsg());
                    chatUser.setLastMessageType(chat.getType());
                }

            }

            chatUsers.add(chatUser);

        }
        for (int i = 0; i < chatUsers.size(); i++) {
            if ("img".equals(chatUsers.get(i).getLastMessageType())) {
                chatUsers.get(i).setLastMessage("[图片]");


            } else if ("file".equals(chatUsers.get(i).getLastMessageType())) {

                chatUsers.get(i).setLastMessage("[文件]");



            }


        }
        for (int i = 0; i < userList.size(); i++) {
            Integer reds = chatMapper.searchMessageCount(userList.get(i).getId(), userId).size();
            chatUsers.get(i).setRed(reds);
if(reds>0){
    chatUsers.get(i).setRedState("");


}else{
    chatUsers.get(i).setRedState("none");

}



        }
        for (int i = 0; i < userList.size(); i++) {

            if(chatMapper.searchUserInfo(userList.get(i).getId())!=null){

                String photo = chatMapper.searchUserInfo(userList.get(i).getId()).getPhoto();

                chatUsers.get(i).setPhoto(photo);
            }
        }
        for(int i = 0; i < userList.size(); i++){



            chatUsers.get(i).setChatList(readMessage(userList.get(i).getId(),userId));

        }


        System.out.println(chatUsers.toString());
        return chatUsers;
    }

    @Override
    public String creatAllMessageTXT(Integer userId1, Integer userId2) {
        List<Chat> chatList = chatMapper.searchAllMessage(userId1, userId2);
        String chatLog="";
        User user1=chatMapper.searchUserById(userId1);
        User user2=chatMapper.searchUserById(userId2);
        Map<Integer,String> userMap=new HashMap<Integer,String>();
        userMap.put(userId1,user1.getName());
        userMap.put(userId2,user2.getName());
        for(int i=0;i<chatList.size();i++){
            chatLog+=userMap.get(chatList.get(i).getFromId())+"("+chatList.get(i).getTime()+")"+":"+"\r\n" +chatList.get(i).getMsg()+"\r\n";

        }
        String path = createTXT(userId1,chatLog);
        System.out.println("path:" + path);
        return path;
    }


    @Override
    public List<ChatBuffer> readMessage(Integer userId1, Integer userId2) {
        List<ChatBuffer> chatList = chatMapper.searchMessageCount(userId1, userId2);

        for(int i=0;i<chatList.size();i++){
            if((chatList.get(i).getMsg().endsWith(".doc")) || (chatList.get(i).getMsg().endsWith(".docx"))){
                chatList.get(i).setIcon("/zzlp/img/word.jpg");
            }else if (chatList.get(i).getMsg().endsWith(".xls")) {
                chatList.get(i).setIcon("/zzlp/img/excel.jpg");
            } else if (chatList.get(i).getMsg().endsWith(".txt")) {
                chatList.get(i).setIcon("/zzlp/img/txt.jpg");
            } else if ((chatList.get(i).getMsg().endsWith(".zip")) || (chatList.get(i).getMsg().endsWith(".rar"))) {
                chatList.get(i).setIcon("/zzlp/img/zip.jpg");
            }


        }
        //chatMapper.readMessage(userId1,userId2);
        return chatList;
    }

    @Override
    public void readMessageEnd(Integer userId1, Integer userId2) {
        chatMapper.readMessage(userId1, userId2);
    }

    @Override
    public String searchAvatar(Integer userId) {

        String avatar=chatMapper.searchUserById(userId).getImg();
        return avatar;
    }


    public String createTXT(Integer userId, String str) {
        Date date = new Date();
        String path = PropertyUtil.prop.getProperty("path.chatLog") + date.getTime() + userId + ".txt";
        try {
            File file = new File(path);
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(str);
            bw.close();
            System.out.println("Done");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }


}
